import { queryCurrent, fakeUserDetails, fakeLoginOut } from '../servers/user';
import { fakeAccountLogin } from '../servers/login';
import { Toast } from 'antd-mobile';

import { UserModelType } from './types'
// model是一个对象，由namespace， state， effects, reducers
const UserModel: UserModelType = {
  namespace: 'user',
  state: {
    currentUser: {},
    detail: {
      name: '',
      icon: '',
      userid: ''
    }
  },
  effects: {
    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);

      yield put({ type: 'saveUser', payload: { currentUser: { ...response } } });
    },
    *login({ payload }, { call, put }) {
      const res = yield call(fakeAccountLogin, payload);
      if (res.status === 1) {
        yield put({ type: 'saveUser', payload: { currentUser: { ...res } } });
      } else {
        Toast.fail(res.msg || '系统开小差，请稍后再试~');
      }
    },
    *userDetails(_, { call, put }) {
      const res = yield call(fakeUserDetails)
      yield put({
        type: 'saveUser', payload: {
          detail: { ...res }
        }
      })
    },
    *userLogOut(_, { call, put }) {
      const res = yield call(fakeLoginOut)
      yield put({
        type: 'clearUser', payload: {
          currentUser: {}, details: {}
        }
      })
    }
  },
  reducers: {
    saveUser(state, action) {
      return {
        ...state, ...action.payload
      };
    },
    clearUser(state, action) {
      return {
        ...state, ...action.payload
      }
    }

  },
};

export default UserModel;
